package Dao;

import DBCPUtil.DBCPUtil;
import Dto.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDao {
    QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource());
    //普通用户登录
    public User login(String username) throws SQLException {
        String sql = "select * from login where username=?";
        User user = qr.query(sql,new BeanHandler<>(User.class),username);
        return user;
    }
//    //超级用户登录
//    public Super superLogin(String username) throws SQLException {
//        String sql = "select * from super where superName=?";
//        Super Super = qr.query(sql,new BeanHandler<>(Super.class),username);
//        return Super;
//    }
    //预注册
    public User register(String username) throws SQLException {
        String sql = "select * from login where username=?";
        User user = qr.query(sql,new BeanHandler<>(User.class),username);
        return user;
    }
    //注册(包含超级用户)
    public void addRegister(User user) throws SQLException {
        String sql = "insert into login(id,username,password,nickname,state) value(null,?,?,?,?)";
        qr.update(sql,user.getUsername(),user.getPassword(),user.getNickname(),"true");
    }
    //个人中心预修改
    public User preUpdateLogin(String nickname) throws SQLException {
        String sql = "select * from login where nickname = ?";
        User user = qr.query(sql,new BeanHandler<>(User.class),nickname);
        return user;
    }
    //个人中心修改
    public void updateLogin(User user) throws SQLException {
        String sql = "update login set password=? where id = ?";
        qr.update(sql,user.getPassword(),user.getId());
    }
    //管理员添加用户(注册管理员账户)
    public void addUser(User user) throws SQLException {
        String sql = "insert into login(id,username,password,nickname,state) value(null,?,?,?,?)";
        qr.update(sql,user.getUsername(),user.getPassword(),user.getNickname(),"true");
    }
    //分页查询
    public List<User> selectUserList(Integer pageNum)throws SQLException{
        String selectSql = "select * from login limit ?,?";
        List<User> list = qr.query(selectSql,new BeanListHandler<>(User.class),(pageNum-1)*10,10);
        return list;
    }
    //有多少条数据
    public Long selectUserCount() throws SQLException{
        String selectSql = "select count(*) from login";
        Long count = qr.query(selectSql,new ScalarHandler<>());
        return count;
    }
    //启用
    public void updateEnable(Integer id) throws SQLException {
        String sql = "update login set state=? where id=?";
        qr.update(sql,"true",id);
    }
    //禁用
    public void updateDisable(Integer id) throws SQLException {
        String sql = "update login set state=? where id=?";
        qr.update(sql,"false",id);
    }
}
